//
//  VideoGridCell.m
//  AVPlayerDemo
//
//  Created by YIDAOMAC on 2024/1/17.
//

#import "VideoGridCell.h"
#import "VideoInfo.h"
#import <AVKit/AVKit.h>
#import <SDWebImage/SDWebImage.h>
#import <KTVHTTPCache/KTVHTTPCache.h>

@interface VideoGridCell ()

///
@property(nonatomic, strong) AVPlayerLayer *playerLayer;

///
@property(nonatomic, strong) AVPlayer *player;

///图片
@property(nonatomic, readonly) UIImageView *imageView;

///
@property(nonatomic, readonly) UILabel *textLabel;

@end

@implementation VideoGridCell

@synthesize playing;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 60)];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
        [self.contentView addSubview:_imageView];
        
        CGRect rect = CGRectMake(0, CGRectGetMaxY(_imageView.frame) + 10, CGRectGetWidth(frame), 50);
        _textLabel = [[UILabel alloc] initWithFrame:rect];
        _textLabel.numberOfLines = 2;
        _textLabel.textColor = UIColor.blackColor;
        [self.contentView addSubview:_textLabel];
        
        self.contentView.backgroundColor = UIColor.whiteColor;
        self.contentView.layer.cornerRadius = 8;
        self.contentView.layer.masksToBounds = YES;
    }
    return self;
}

- (AVPlayerLayer *)playerLayer
{
    if (!_playerLayer) {
        AVPlayerLayer *layer = [AVPlayerLayer layer];
        layer.frame = self.imageView.frame;
        layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.contentView.layer addSublayer:layer];
        _playerLayer = layer;
    }
    
    return _playerLayer;
}

- (void)setInfo:(VideoInfo *)info
{
    if (_info != info) {
        _info = info;
        [self.imageView sd_setImageWithURL:_info.imageURL placeholderImage:nil];
        self.textLabel.text = _info.desc;
        KTVHCDataRequest *request = [[KTVHCDataRequest alloc] initWithURL:_info.videoURL headers:nil];
        KTVHCDataLoader *loader = [KTVHTTPCache cacheLoaderWithRequest:request];
        [loader prepare];
    }
}

- (NSURL *)videoURL
{
    return self.info.videoURL;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _playerLayer.frame = self.imageView.frame;
}

- (void)startPlayWithPlayer:(AVPlayer *)player
{
    self.playing = YES;
    self.playerLayer.player = player;
}

- (void)stopPlayWithCurrentImage:(UIImage *)currentImage
{
    self.playing = NO;
    [self.playerLayer.player pause];
    self.playerLayer.player = nil;
    if (currentImage) {
        self.imageView.image = currentImage;
    }
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    [self stopPlayWithCurrentImage:nil];
}

@end
